package screen;

import java.util.Vector;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import main.GameCanvas;
import main.NuoiThuMidlet;
import model.Command;
import model.IAction;
import model.PlayerInfo;
import model.Position;
import service.GlobalService;
import utilities.GameResource;
import utilities.TField;
import utilities.TileMap;
import animation.FlyText;
import font.BitmapFont;

public abstract class PlayGameScr extends Screen implements IChatable {
	public PlayerInfo[] m_arrPlayers;

	public Position[] m_arrPos;
	public String[] m_arrChatContent;
	
	public int m_iMaxPlayer = 2;
	private boolean m_bIsPlaying = false;
	public int m_iCurrentTime;
	public int m_iPlayerInTurn;
	public boolean m_bMyReady = false;
	public byte m_iRoomID;
	public byte m_iBoardID;
	public int m_iOwnerID;
	public int m_iMoney;
	public boolean m_bIsDisplayAnimal = false;
	
	public Image m_imgBackground;
			
	protected Command beginCmd;
	protected Command readyCmd;
	protected Command menuNormalCmd;
	protected Command menuOwnerCmd;
	
	protected Command makeFriendCmd;
	
	public PlayGameScr(int maxPlayer){
		
		makeFriendCmd = new Command(GameResource.addFreind, new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				Vector v = new Vector();
				
				int i;
				for(i = 0; i < m_arrPlayers.length; i++){
					if(m_arrPlayers[i] != null && m_arrPlayers[i].m_iId != NuoiThuMidlet.m_myPlayerInfo.m_iId && m_arrPlayers[i].m_iId != -1){
						final int playerId = m_arrPlayers[i].m_iId;
						final String playerName = m_arrPlayers[i].m_UserName;
						v.addElement(new Command(playerName, new IAction() {
							public void perform() {
								// TODO Auto-generated method stub
				                GlobalService.gI().doRequestAddFriend(playerId);
				                GameCanvas.startOKDlg(GameResource.requestFriendSent + playerName);
							}
						}));
					}
				}				
				
				GameCanvas.menu.startAt(v, 0);
			}
		});
		
		//init command
		beginCmd = new Command("Bắt đầu", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				boolean bFound = false;
				int i;
				int count = 0;
				for(i = 0; i < m_iMaxPlayer; i++)
					if(m_arrPlayers[i].m_iId != -1){
						if(!m_arrPlayers[i].isReady && m_arrPlayers[i].m_iId != NuoiThuMidlet.m_myPlayerInfo.m_iId){
							bFound = true;
							break;
						}
						count++;
					}
				if(bFound)
					GameCanvas.startOKDlg("Còn người chưa sẵn sàng");
				else if(count == 1)
					GameCanvas.startOKDlg("Chưa đủ người chơi");
				else{
					GameCanvas.startWaitDlg(GameResource.plzWait);
					GlobalService.gI().startGame(m_iRoomID, m_iBoardID);
				}
			}
		});
		
		readyCmd = new Command("Sẵn sàng", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				if(m_bIsPlaying)
					GameCanvas.startOKDlg("Ván đang chơi, không thể sẵn sàng");
				else{
					if(NuoiThuMidlet.m_myPlayerInfo.getMoney(0) < m_iMoney){
						GameCanvas.startOKDlg("Không đủ tiền cược");
						return;
					}
					m_bMyReady = !m_bMyReady;
					GameCanvas.startWaitDlg(GameResource.plzWait);
					GlobalService.gI().ready(m_iRoomID, m_iBoardID, m_bMyReady);
				}
			}
		});
		
		menuNormalCmd = new Command(GameResource.menu, new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				Vector v = new Vector();
				
				if(countPlayer() > 1)
					v.addElement(makeFriendCmd);
				
				v.addElement(m_viewMsgCmd);
				
				Command c = new Command("Rời sàn", new IAction() {
					
					public void perform() {
						// TODO Auto-generated method stub
						if(m_bIsPlaying){
							GameCanvas.startOKDlg("Nếu thoát game bạn sẽ bị xử thua. Bạn có muốn thoát", new IAction() {
								
								public void perform() {
									// TODO Auto-generated method stub
									doLeaveBoard();
								}
							});
						}
						else
							doLeaveBoard();
					}
				});
				v.addElement(c);
				
				
				GameCanvas.menu.startAt(v, 0);
			}
		});
		
		menuOwnerCmd = new Command(GameResource.menu, new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				Vector v = new Vector();
				
				if(countPlayer() > 1)
					v.addElement(makeFriendCmd);
				
				Command c = new Command("Đặt cược", new IAction() {
					
					public void perform() {
						// TODO Auto-generated method stub
						
						GameCanvas.inputDlg.setInfo("Tiền cược", new IAction() {
							public void perform() {
								int money = 0;
								try{
									money = Integer.parseInt(GameCanvas.inputDlg.tfInput.getText());
								}
								catch(Exception ex){
									GameCanvas.startOKDlg("Tiền cược không hợp lệ");
									return;
								}
								
								GlobalService.gI().setMoney(m_iRoomID, m_iBoardID, money);
								GameCanvas.endDlg();
							}
						}, TField.INPUT_TYPE_NUMERIC);
						GameCanvas.inputDlg.show();
						
					}
				});
				v.addElement(c);
				
				c = new Command("Đặt mật khẩu", new IAction() {
					public void perform() {
						// TODO Auto-generated method stub
						GameCanvas.inputDlg.setInfo("Mật khẩu", new IAction() {
							public void perform() {						
								if(GameCanvas.inputDlg.tfInput.getText() != ""){
									GlobalService.gI().setPassword(m_iRoomID, m_iBoardID, GameCanvas.inputDlg.tfInput.getText());
								}
								GameCanvas.endDlg();
							}
						}, TField.INPUT_ALPHA_NUMBER_ONLY);
						GameCanvas.inputDlg.show();
					}
				});
				v.addElement(c);
				
				c = new Command("Kick", new IAction() {
					
					public void perform() {
						// TODO Auto-generated method stub
						int i;
						Vector vt = new Vector();
						for(i=0;i<m_arrPlayers.length;i++){
							final int pID = m_arrPlayers[i].m_iId; 
							if(pID != -1 && pID != m_iOwnerID){
								Command c = new Command(m_arrPlayers[i].m_strName, new IAction() {
									
									public void perform() {
										// TODO Auto-generated method stub
										GlobalService.gI().kick(m_iRoomID, m_iBoardID, pID);
									}
								});
								
								vt.addElement(c);
							}
						}
						if(vt.size()> 0)
							GameCanvas.menu.startAt(vt, 0);
						else
							GameCanvas.startOKDlg("Không có người chơi");
					}
				});
				v.addElement(c);
				
				v.addElement(m_viewMsgCmd);
				
				c = new Command("Rời sàn", new IAction() {
					
					public void perform() {
						// TODO Auto-generated method stub
						if(m_bIsPlaying){
							GameCanvas.startOKDlg("Nếu thoát game bạn sẽ bị xử thua. Bạn có muốn thoát", new IAction() {
								
								public void perform() {
									// TODO Auto-generated method stub
									doLeaveBoard();
								}
							});
						}
						else
							doLeaveBoard();
					}

					
				});
				v.addElement(c);
				
				GameCanvas.menu.startAt(v, 0);

			}
		});
		
		
		m_iMaxPlayer = maxPlayer;
		
		m_arrPlayers = new PlayerInfo[m_iMaxPlayer];
		m_arrPos = new Position[m_iMaxPlayer];
		
		
		m_bEndGame = false;
		m_bIsPlaying = false;
		
		TileMap.instance.loadMap(TileMap.LOGIN_MAP);
		m_imgBackground = Image.createImage(GameCanvas.w, GameCanvas.h);
		Graphics g = m_imgBackground.getGraphics();
        g.setColor(0x8be2ff);
        g.fillRect(0, 0, GameCanvas.w, GameCanvas.h);
        
        int hMap = TileMap.m_iHeightTile * TileMap.instance.m_gardenMap.m_iMapHeight;
        int yTrees = GameCanvas.h - hMap;
        if(m_iMaxPlayer == 2){
        	yTrees = GameCanvas.h - GameCanvas.hBottomBar - (hMap >> 1);
        }		
        
		int i = 0;
		int yTmp = yTrees - GameResource.instance.imgScreenLogin.getHeight() + 24;
		int tmpW = GameResource.instance.imgScreenLogin.getWidth();
        for(i = 0; i < GameCanvas.w; i += tmpW){
        	g.drawImage(GameResource.instance.imgScreenLogin, i, yTmp, Graphics.LEFT | Graphics.TOP);
        }        
        
        //draw background to image buffer
        TileMap.instance.paintMap(g, 0 , yTrees);
        int wMap = TileMap.instance.m_gardenMap.m_iMapWidth * TileMap.m_iWidthTile;
        if(wMap < GameCanvas.w){
        	//adding tile for large screen
        	tmpW = (GameCanvas.w - wMap)/TileMap.m_iWidthTile + 1;
        	TileMap.instance.paintMap(g, wMap, yTrees, tmpW, TileMap.instance.m_gardenMap.m_iMapHeight);
        }
       
        
        g.drawImage(GameResource.instance.imgTree, GameCanvas.hw + 50, yTrees+14, Graphics.LEFT | Graphics.BOTTOM);
        g.drawImage(GameResource.instance.imgTree, GameCanvas.hw - 80, yTrees+18, Graphics.LEFT | Graphics.BOTTOM);
       
        tmpW = GameResource.instance.imgFance.getWidth();
        int tmp = GameCanvas.w/3;
        yTrees -= (GameResource.instance.imgFance.getHeight()>>1);
        for(i = 0; i < tmp; i+= tmpW){
        	g.drawImage(GameResource.instance.imgFance, i, yTrees+4, Graphics.LEFT | Graphics.TOP);
        }
        tmp = GameCanvas.w2d3;
        for(i = GameCanvas.w; i > tmp; i -= tmpW){
        	g.drawImage(GameResource.instance.imgFance, i, yTrees+4, Graphics.RIGHT | Graphics.TOP);
        }
	}
	
	public PlayerInfo findPlayer(int playerID){
		int i, count = m_arrPlayers.length;
		for(i = 0; i < count; i++){
			if(m_arrPlayers[i].m_iId == playerID)
				return m_arrPlayers[i];
		}
		return null;
	}
	
	public int findPlayerPos(int playerID){
		int i, count = m_arrPlayers.length;
		for(i = 0; i < count; i++){
			if(m_arrPlayers[i].m_iId == playerID)
				return i;
		}
		return -1;	
	}
	
	public void close() {
		// TODO Auto-generated method stub
		
	}

	public void update() {
		// TODO Auto-generated method stub
	}
	
	public void keyPress(int keyCode) {
		ChatTextField.gI().startChat(keyCode, this);
		super.keyPress(keyCode);
	}
	
	public void paint(Graphics g){
		if(!m_bIsPlaying){
			g.translate(-g.getTranslateX(), -g.getTranslateY());
			g.setClip(0, 0, GameCanvas.w, GameCanvas.h);
			g.drawImage(m_imgBackground, 0, 0, 0);

			int i, count = m_arrPlayers.length;
			for(i = 0; i < count; i++){
				PlayerInfo p = m_arrPlayers[i];
				if(p!= null && p.m_iId != -1){
					p.paintInBoard(g, m_arrPos[i].x, m_arrPos[i].y, m_arrPos[i].anchor, m_bIsDisplayAnimal);
				}
			}
		
			//paint top bar
			PaintPopup.paintTopBar(g);
			
			//paint icon game
			GameResource.instance.m_frameIconItems.drawFrame(RoomListScr.m_iIconGame, 2, -1, 0, g);
			
			//paint board info
			BitmapFont.drawBoldFont(g, "Khu " + m_iRoomID + " - Sân " + m_iBoardID, 30, 10, 0xffffff, Graphics.LEFT | Graphics.VCENTER);
			
			PaintPopup.paintMoney(g, GameCanvas.w - 105, 3, NuoiThuMidlet.m_myPlayerInfo.m_iMoney);
			
			//paint pet
			PaintPopup.paintBoxClock(g, GameCanvas.hw - 10, GameCanvas.hBottomBar + 20, "" + m_iMoney);
		}
		else
		{
			if(m_strChatContent != null){
				PaintPopup.paintBox(g, 0, 0, GameCanvas.w, 20, 1, 0xffffff, 0x000000);
				BitmapFont.drawNormalFont(g, m_strChatContent, 5, 10, 0x000000, Graphics.LEFT | Graphics.VCENTER);
				m_iTimeChat++;
				if(m_iTimeChat > 50){
					m_strChatContent = null;
					m_iTimeChat = 0;
				}
			}
		}
				
		if (m_nMsg > 0) {
            BitmapFont.drawOutlinedString(g, m_nMsg + " ", GameCanvas.w - 20, 25, 0xffff00, 0x000000, Graphics.RIGHT | Graphics.VCENTER);
            g.drawImage(GameResource.instance.imgMesssage, GameCanvas.w - 20, 20, 0);
        }
				
		super.paint(g);
	}
	
	public void setPlayer(PlayerInfo p, int seat) {
		// TODO Auto-generated method stub
		if(seat >=0 && seat < m_iMaxPlayer){
			m_arrPlayers[seat] = p;
		}
		
		p.isReady = false;
		p.isOwner = false;
	}
	
	private void doLeaveBoard() {
		// TODO Auto-generated method stub
		GameCanvas.startWaitDlg(GameResource.plzWait);
		GlobalService.gI().leaveBoard(m_iRoomID, m_iBoardID);
		GlobalService.gI().requestBoardList(m_iRoomID);
	}
	
	public void switchToMe(byte roomID1, byte boardID, Vector vtPlayers,
			int ownerID, int money) {
		// TODO Auto-generated method stub
		super.switchToMe();
		m_bIsPlaying = false;
		m_bMyReady = false;
		readyCmd.caption = "Sẵn sàng";
		
    	int i, count = vtPlayers.size();
    	for(i=0;i<count;i++){
    		m_arrPlayers[i] = (PlayerInfo)vtPlayers.elementAt(i);	
    		if(m_arrPlayers[i].m_iId == ownerID)
    			m_arrPlayers[i].isOwner = true;
    	}
    	
    	m_iRoomID = roomID1;
    	m_iBoardID = boardID;
    	m_iMoney = money;
    	    	
    	setOwner(ownerID);
    	
    	System.gc();
	}

	public void resetReady() {
		for (int i = 0; i < m_iMaxPlayer; i++) {
			m_arrPlayers[i].isReady = false;
		}
		readyCmd.caption = "Sẵn sàng";
		m_bMyReady = false;
	}
	
	public void playerLeave(int iDLeave) {
		// TODO Auto-generated method stub
		PlayerInfo p = getPlayerInfo(iDLeave);	
		if (p != null && p.m_iId != NuoiThuMidlet.m_myPlayerInfo.m_iId) {
			p.m_iId = -1;
			p.m_strName = "";
			p.m_sExperience = 0;
			p.isReady = false;			
			p.isOwner = false;
		}
	}

	public void setMoney(int money) {
		// TODO Auto-generated method stub
		m_iMoney = money;
		resetReady();
	}	

	public PlayerInfo getPlayerInfo(int id){
		for(int i = 0; i < m_iMaxPlayer; i++){
			if(m_arrPlayers[i].m_iId == id)
				return m_arrPlayers[i];
		}
		return null;
	}
	
	public void stopGame(){
		m_bMyReady = false;
		m_bIsPlaying = false;
		NuoiThuMidlet.m_myPlayerInfo.isReady = false;
		setOwner(m_iOwnerID);
		readyCmd.caption = "Sẵn sàng";
	}
	
	public void startGame(){
		m_bIsPlaying = true;
		m_cmdLeft = menuNormalCmd;
	}
	
	public boolean isPlaying(){
		return m_bIsPlaying;
	}
	
	public void setOwner(int iDNewOwner) {
		// TODO Auto-generated method stub
		m_iOwnerID = iDNewOwner;
		if(isPlaying())
			return;
		
		PlayerInfo p = getPlayerInfo(iDNewOwner);		
		if (p != null){
			p.isReady = true;
			p.isOwner = true;
		}
		
		if(m_iOwnerID == NuoiThuMidlet.m_myPlayerInfo.m_iId){
    		m_cmdLeft = menuOwnerCmd;
    		m_cmdCenter = beginCmd;
    	}
    	else
    	{
    		m_cmdLeft = menuNormalCmd;        	
    		m_cmdCenter = readyCmd;
    	}		
	}

	public void setReady(int iD, boolean isReady) {
		// TODO Auto-generated method stub
		PlayerInfo p = getPlayerInfo(iD);
		if (p != null) {
			p.isReady = isReady;
			if(p.m_iId == NuoiThuMidlet.m_myPlayerInfo.m_iId){
				m_bMyReady = isReady;
			
				GameCanvas.endDlg();
				
				if(m_bMyReady)
				{
					readyCmd.caption = "Ko sẵn sàng";
				}
				else
				{
					readyCmd.caption = "Sẵn sàng";
				}
			}
		}
	}

	public boolean m_bEndGame = false;
	public int m_iIdWinner;
	public void onBonusMoney(int playerId, int value, String text) {
		// TODO Auto-generated method stub
		int pos = findPlayerPos(playerId);
		PlayerInfo p = findPlayer(playerId);
		if(pos != -1){
			FlyText f;
			if(m_bEndGame){
				if(playerId == NuoiThuMidlet.m_myPlayerInfo.m_iId && playerId == m_iIdWinner){
					f = new FlyText();
					f.startEffect(text, m_arrPos[pos].x, m_arrPos[pos].y, 0xffff00, 0x000000);
					
					f = new FlyText();
					f.startEffect("" + value, m_arrPos[pos].x, m_arrPos[pos].y + 10, 0xffff00, 0x000000);
				}
				m_bEndGame = false;	
			}
			else{
				f = new FlyText();
				f.startEffect(text, m_arrPos[pos].x, m_arrPos[pos].y, 0xffff00, 0x000000);
				
				f = new FlyText();
				f.startEffect("" + value, m_arrPos[pos].x, m_arrPos[pos].y + 10, 0xffff00, 0x000000);
			}
			
		}
		if(playerId == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			NuoiThuMidlet.m_myPlayerInfo.setMoney(NuoiThuMidlet.m_myPlayerInfo.getMoney(0) + value, 0);
		}
		if(p != null)
			p.setMoney(p.getMoney(0) + value, 0);
	}
	public void onChatFromMe(String text) {
		if (text.trim().equals(""))
			return;
		GlobalService.gI().chatToBoard(m_iRoomID, m_iBoardID, text);
		showChat(NuoiThuMidlet.m_myPlayerInfo.m_iId, text);
	}
	
	public String m_strChatContent = null;
	public int m_iTimeChat = 0;
	public void showChat(int fromID, String text) {
		PlayerInfo p = findPlayer(fromID);
		if(p != null && p.m_iId != -1){
			if(m_bIsPlaying){
				m_strChatContent = p.m_strName + ": " + text;
				m_iTimeChat = 0;
			}
			else{
				p.chat(text);
			}
		}
	}
	public int countPlayer(){
		int i;
		int count = 0;
		for(i = 0; i < m_arrPlayers.length; i++){
			if(m_arrPlayers[i] != null && m_arrPlayers[i].m_iId != -1)
				count++;
		}
		return count;
	}
	public void paintMarqueeMsg(Graphics g){
		if(m_bIsPlaying){
			PaintPopup.paintBox(g, 0, 0, GameCanvas.w, 20, 1, 0x000000, 0x000000);
	    	BitmapFont.drawBoldFont(g, m_strMarqueeMsg, m_iPosXMsg, 10, 0xffffff, Graphics.LEFT | Graphics.VCENTER);	
		}
		else
		{
			PaintPopup.paintBox(g, 0, GameCanvas.hBottomBar, GameCanvas.w, 20, 1, 0x000000, 0x000000);
	    	BitmapFont.drawBoldFont(g, m_strMarqueeMsg, m_iPosXMsg, GameCanvas.hBottomBar + 10, 0xffffff, Graphics.LEFT | Graphics.VCENTER);
		}
		
		m_iTimeDisplay++;
		m_iPosXMsg-- ;
		if(m_iPosXMsg <= - m_iStrWidth){
			m_iPosXMsg = GameCanvas.w;
		}
		if(m_iTimeDisplay > 1000){
			m_iTimeDisplay = 0;
			m_strMarqueeMsg = null;
		}
	}
}